﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Web;
using WebApi.Helpers;
using WebApi.Model;
using Log = WebApi.Model.Log;

namespace WebApi.Controllers
{
    /// <summary>
    /// 控制器基类
    /// </summary>
    //[Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class BaseController : ControllerBase
    {
        /// <summary>
        /// 当前访问用户Id
        /// </summary>
        protected virtual int UserId { get; set; }
        /// <summary>
        /// 当前访问用户日志名
        /// </summary>
        protected virtual string UserName { get; set; }
        /// <summary>
        /// 接口返回实体
        /// </summary>
        public ReturnModel result = new ReturnModel();
        /// <summary>
        /// 日志
        /// </summary>
        public readonly ILogger logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public BaseController(ILogger logger)
        {
            var httpcontext = HttpContextHelper.Current;
            UserId = int.Parse(string.IsNullOrWhiteSpace(httpcontext?.Request.Headers["UserId"]) ? "0" : httpcontext?.Request.Headers["UserId"].ToString());
            UserName = string.IsNullOrWhiteSpace(httpcontext?.Request.Headers["UserName"]) ? "0" : httpcontext?.Request.Headers["UserName"].ToString();
            UserName = HttpUtility.UrlDecode(UserName);

            this.logger = logger;
            this.logger.LogDebug($"UserId={UserId},UserName={UserName},Path={httpcontext ? .Request.Path}");
        }

        /// <summary>
        /// 向数据库写入日志
        /// </summary>
        /// <param name="tableName">操作表名</param>
        /// <param name="opeType">操作类型</param>
        /// <param name="opeDetail">操作详情</param>
        /// <param name="opeResult">操作结果</param>
        /// <param name="remark">备注</param>
        protected void LogToDB(string tableName, string opeType, string opeDetail, string opeResult = "", string remark = "")
        {
            Log log = new Log { UserID = UserId, AddTime = DateTime.Now, UserName = UserName, TableName = tableName, OpeType = opeType, OpeDetail = opeDetail, OpeResult = opeResult, Remark = remark };
            logger.LogInformation(JsonConvert.SerializeObject(log));
            DbHelper.Log.InsertAsync(log);
        }
        /// <summary>
        /// 向数据库写入日志
        /// </summary>
        /// <param name="model"></param>
        protected void LogToDB(Log model)
        {
            model.UserID = UserId;
            model.AddTime = DateTime.Now;
            model.UserName = UserName;
            logger.LogInformation(JsonConvert.SerializeObject(model));
            DbHelper.Log.InsertAsync(model);
        }
    }
}
